package com.flydog.taskManager.repository;

import com.flydog.taskManager.dto.PhaseTaskSearchParam;
import com.flydog.taskManager.entity.PhasedTask;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class PhasedTaskSpecs {

    public static Specification<PhasedTask> attributeLike(String attributeName, String attributeValue) {
        return (root, query, builder) -> {
            return builder.like(root.get(attributeName), "%" + attributeValue + "%");
        };
    }

    public static Specification<PhasedTask> searchSpecs(PhaseTaskSearchParam param, Long userId) {
        return (root, query, builder) -> {
            List<Predicate> list = new ArrayList<Predicate>();
            list.add(builder.equal(root.get("userId").as(Long.class), userId));
            if (param.getName() != null && param.getName().trim().length() > 0) {
                list.add(builder.like(root.get("name"), "%" + param.getName() + "%"));
            }
            if (param.getTarget() != null && param.getTarget().trim().length() > 0) {
                list.add(builder.like(root.get("target"), "%" + param.getTarget() + "%"));
            }
            if (param.getTags() != null && param.getTags().trim().length() > 0) {
                list.add(builder.like(root.get("tags"), "%" + param.getTags() + "%"));
            }
            if (param.getImportance() != null) {
                list.add(builder.equal(root.get("importance").as(Integer.class), param.getImportance()));
            }
            if (param.getProcessStatus() != null) {
                list.add(builder.equal(root.get("processStatus").as(Integer.class), param.getProcessStatus()));
            }
            if (param.getBeginStart() != null && param.getBeginFinish() != null) {
                list.add(builder.between(root.get("begin").as(Date.class), param.getBeginStart(), param.getBeginFinish()));
            }
            if (param.getEndStart() != null && param.getEndFinish() != null) {
                list.add(builder.between(root.get("end").as(Date.class), param.getEndStart(), param.getEndFinish()));
            }
            Predicate[] p = new Predicate[list.size()];
            return builder.and(list.toArray(p));
        };
    }


}
